package com.bwie.controller;

import com.bwie.bean.Article;
import com.bwie.bean.Tag;
import com.bwie.service.ArticleService;
import com.bwie.util.FileUploadUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class ArticleController {

    @Autowired
    ArticleService articleService;

    @RequestMapping("list.do")
    public String list(
            @RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
            Model model,
            String title,
            String content,
            String tid
    ){
        Map map = new HashMap();
        map.put("title",title);
        map.put("content",content);
        map.put("tid",tid);
        PageHelper.startPage(pageNum,2);
        List<Article>list=articleService.list(map);
        PageInfo pageInfo = new PageInfo(list);
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("map",map);
        return "list";
    }
    //动态获取所有标签
    @RequestMapping("listTag.do")
    @ResponseBody
    public List<Tag>listTag(){
        List<Tag>listTag=articleService.listTag();
        return listTag;
    }
    //删除
    @RequestMapping("delAll.do")
    @ResponseBody
    public Object delAll(String aid){
        int a=articleService.delAll(aid);
        return a;
    }
    //添加
    @RequestMapping("toadd.do")
    public String toadd(){
        return "add";
    }
    //添加
    @RequestMapping("add.do")
    @ResponseBody
    public Object add(Article article, MultipartFile photo, HttpSession session,Integer[]tids){
        if (photo!=null){
            String upload = FileUploadUtil.load(session, photo, "upload");
            article.setPic(upload);
        }
        int a=articleService.add(article,tids);
        return a;
    }
    //修改toupdate
    @RequestMapping("toupdate.do")
    public String toupdate(){
        return "update";
    }
    //添加
    @RequestMapping("update.do")
    @ResponseBody
    public Object update(Article article, MultipartFile photo, HttpSession session,Integer[]tids){
        if (photo!=null){
            String upload = FileUploadUtil.load(session, photo, "upload");
            article.setPic(upload);
        }
        int a=articleService.update(article,tids);
        return a;
    }
    //回显
    @RequestMapping("listHui.do")
    @ResponseBody
    public Article listHui(Integer aid){
        Article listHui=articleService.listHui(aid);
        return listHui;
    }
}
